package com.msblearn.C_013;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 有两个：CopyOnWriteArrayList和CopyOnWriteSet
 * CopyOnWriteArrayList:写的时候加了锁。效率比较低。读:不用加锁。
 */
public class T002_CopyOnWriteArrayList {

    public static void main(String[] args) {
        List<String> lists =
//                new ArrayList<>();
//                new Vector<>();
                new CopyOnWriteArrayList<>();
        Random r = new Random();
        Thread[] tds = new Thread[100];
        for(int i=0;i<tds.length;i++){
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    for(int i=0;i<1000;i++){
                        lists.add("a"+r.nextInt(10000));
                    }
                }
            };
            tds[i] = new Thread(task);
        }
        runAndComputeTime(tds);
        System.out.println(lists.size());
    }


    private static void runAndComputeTime(Thread[] ths) {
        long s1 = System.currentTimeMillis();
        Arrays.asList(ths).forEach(t->t.start());
        Arrays.asList(ths).forEach(t->{
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long s2 = System.currentTimeMillis();
        System.out.println(s2 - s1);
    }
}
